<template>
  <div class="page">
    <!-- 头部导航 -->
    <header class="head flex jc-sb aic bg-fff  res">
      <p @click="$router.go(-1)" class="act f14">
        <i class="iconfont icon-iconfontjiantouzuo"></i> 返回
      </p>
      <p class="cartText abs">购物车</p>
      <p class="act f14" @click="editing = !editing">
        {{ editing ? "完成" : "编辑" }}
      </p>
    </header>
    <!-- 产品列表 -->
    <div class="shoppingList">
      <div
        class="product flex aic bg-fff"
        v-for="(item) in cartList"
        :key="item.cartId">
        <base-checkbox v-model="item.flag"></base-checkbox>
        <div class="dec flex fg1">
          <img class="ml-15 bgGrey" :src="item.imgUrl" alt="" height="95px" />
          <div class="text flex fdc jc-sb">
            <p>{{ item.masterName }}</p>
            <p class="flex jc-sb aic">
              <span class="act">￥{{ item.price / 100 }}</span>
              <span v-if="editing" class="opt-box">
                <a class="opt" @click="updateBuyNum(item, 1)">+</a>
                <a class="num ml-10 mr-10">x {{ item.buyNum }}</a>
                <a class="opt" @click="updateBuyNum(item, -1)">-</a>
              </span>
              <span v-else class="num ml-10 mr-10">x {{ item.buyNum }}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部结算 -->
    <div class="closingBox flex jc-sb aic bg-fff fixed">
      <div class="all select flex" @click="selectAll = !selectAll">
        <base-checkbox @change="changeAll" v-model="selectAll"></base-checkbox>
        <span class="ml-10 f14" >{{selectAll ? "全不选" : "全选"}}</span>
      </div>
      <div class="flex aic">
        <span class="f14">合计 :</span>
        <span class="act f18">¥ {{ totalMoney.toFixed(2) }}</span>
        <span class="confirm ml-10" @click="delCart" v-if="editing">删除</span>
        <span @click="submit" class="confirm ml-10" v-else>结算</span>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script>


import Footer from "@/components/Footer";
import $axios from "@/utils/request";
export default {
  components: {
    Footer,
  },
  data() {
    return {
      cartList: [],
      editing: false,
      selectAll: false,
      selectList: [],
      totalMoney: 0
    };
  },
  created() {
    this.getCartList();
  },
  methods: {
    async submit() {
      //1.检查用户有没有选择商品, 没有则提示用户
      if (this.selectList.length === 0) {
        this.$toast.fail("您还没选择商品,请选择商品");
        return false;
      }
      //2.发送请求到后台
      try { 
        // 把选中的商品id放入到一个数组里
        let cartId = this.selectList.map(item => item.cartId);
        // 请求参数
        let data = {
          cartId,
          totalMoney: this.totalMoney
        };
        let res = await this.$axios.post("/preOrder/add",data); 
        // 从结果里把preOrderId解构出来
        let { preOrderId } = res.result;
        // 跳转到确认订单页面, 并把preOrderId传过去  
        this.$router.push({
          path: '/submit',
          query: {preOrderId}
        })
      } catch (error) {
        console.log(error)
      }
    },
    //全选
    changeAll() {
      if (this.selectAll === true) {
        this.cartList.forEach((item) => {
          item.flag = true;
          this.selectList.push(item);
        });
      } else {
        this.cartList.forEach((item) => {
          item.flag = false;
        });
        this.selectList = [];
      }
    },
    //删除购物车
    async delCart() {
      try {
        //得到选中的商品编号数组
        let cartIdList = this.selectList.map(item => item.cartId);
        let res = await this.$axios.post('/cart/del',{cartId:cartIdList})
        //notInList不被选中的商品
        let notInList = this.cartList.filter(item => {
          return !cartIdList.includes(item.cartId)
        })
        //重新赋值
        this.cartList = notInList;
      } catch (error) {
        console.log(error)
      }
    },
    async getCartList() {
      try {
        let res = await this.$axios.get("/cart/all");
        res.list = res.list.map((item) => {
          return {
            //把item所有属性和值都拿过来
            ...item,
            flag: false,
          };
        });
        this.cartList = res.list;
      } catch (error) {
        console.log(error);
      }
    },
    //购物车数量增删
    async updateBuyNum(item, num) {
      if(item.buyNum ===1 && num === -1) return false
      try {
        let data = {
          cartId: item.cartId,
          buyNum : item.buyNum + num
        }
        let res = await this.$axios.get("/cart/updateNum",data);
        item.buyNum = item.buyNum + num
      } catch (error) {
        console.log(error)
      }
    },
  },
  watch: {
   
    cartList: {
      handler(newList) {
        this.selectList = newList.filter((item) => item.flag);
        if(this.selectList.length === newList.length) {
          this.selectAll = true;
        }else{
          this.selectAll = false;
        }
      },
      deep:true,
    },
    //监听seletList
    selectList: {
      handler(newList) {
        let totalMoney = 0;
        newList.forEach(item=> {
          let money = item.price * item.buyNum/100;
          totalMoney += money
        })
        console.log(totalMoney.toFixed(2))
        this.totalMoney = totalMoney
      },
      deep:true
    }

  },

};
</script>

<style lang="less" scoped>
@import "./shopping.less";

.num {
  color: #999;
}
.opt {
  width: 14px;
  line-height: 14px;
  border: 1px solid #999;
  display: inline-block;
  text-align: center;
}
</style>